<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="我们一直都在说传统的 IO属于阻塞 IO，而 NIO属于非阻塞的 IO. 我一直在理解 阻塞 IO 和 非阻塞 IO 的区别。 看了这么多文章后，今天算是小有所获，可以用形象的语言来表达他们的区别了。  古人学问无遗力，少壮工夫老始成。">
<meta name="keywords" content="NIO">
<meta property="og:type" content="article">
<meta property="og:title" content="NIO-概念理解">
<meta property="og:url" content="http://yoursite.com/2018/04/19/think-nio-mine/index.html">
<meta property="og:site_name" content="ThinkMore">
<meta property="og:description" content="我们一直都在说传统的 IO属于阻塞 IO，而 NIO属于非阻塞的 IO. 我一直在理解 阻塞 IO 和 非阻塞 IO 的区别。 看了这么多文章后，今天算是小有所获，可以用形象的语言来表达他们的区别了。  古人学问无遗力，少壮工夫老始成。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://p5h71khzd.bkt.clouddn.com/%E9%98%BB%E5%A1%9Eio.png">
<meta property="og:image" content="http://p5h71khzd.bkt.clouddn.com/%E9%9D%9E%E9%98%BB%E5%A1%9EIO.png">
<meta property="og:image" content="http://p5h71khzd.bkt.clouddn.com/io%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8.png">
<meta property="og:image" content="http://p5h71khzd.bkt.clouddn.com/%E5%BC%82%E6%AD%A5io.png">
<meta property="og:updated_time" content="2018-07-09T02:48:36.942Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="NIO-概念理解">
<meta name="twitter:description" content="我们一直都在说传统的 IO属于阻塞 IO，而 NIO属于非阻塞的 IO. 我一直在理解 阻塞 IO 和 非阻塞 IO 的区别。 看了这么多文章后，今天算是小有所获，可以用形象的语言来表达他们的区别了。  古人学问无遗力，少壮工夫老始成。">
<meta name="twitter:image" content="http://p5h71khzd.bkt.clouddn.com/%E9%98%BB%E5%A1%9Eio.png">






  <link rel="canonical" href="http://yoursite.com/2018/04/19/think-nio-mine/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>NIO-概念理解 | ThinkMore</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?13172698bcdb7ab00b7d3ec112aae9c1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ThinkMore</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">驽马十驾,功在不舍！</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archives</a>
  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/04/19/think-nio-mine/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="文敦复">
      <meta itemprop="description" content="思考的懒惰是真的懒惰！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ThinkMore">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">NIO-概念理解
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2018-04-19 18:31:20" itemprop="dateCreated datePublished" datetime="2018-04-19T18:31:20+08:00">2018-04-19</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Modified: 2018-07-09 10:48:36" itemprop="dateModified" datetime="2018-07-09T10:48:36+08:00">2018-07-09</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Java基础/" itemprop="url" rel="index"><span itemprop="name">Java基础</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>我们一直都在说传统的 IO属于<em>阻塞 IO</em>，而 <code>NIO</code>属于非阻塞的 IO.</p>
<p>我一直在理解 阻塞 IO 和 非阻塞 IO 的区别。</p>
<p>看了这么多文章后，今天算是小有所获，可以用形象的语言来表达他们的区别了。</p>
<blockquote>
<p>古人学问无遗力，少壮工夫老始成。 </p>
</blockquote>
<a id="more"></a>
<h1 id="需求背景"><a href="#需求背景" class="headerlink" title="需求背景"></a>需求背景</h1><p>我们利用一个需求来进行解释：服务端需要接收多个客户端传输过来的信息，该流程只包含接收部分，至于接收到的数据是通过线程池进行处理还是怎么处理，不属于本章讨论范畴，我们只讨论几种不同的IO的接收流程。</p>
<h1 id="阻塞-IO：BIO"><a href="#阻塞-IO：BIO" class="headerlink" title="阻塞 IO：BIO"></a>阻塞 IO：BIO</h1><p><code>传统的IO</code>是<code>BIO</code> 也称为<code>同步阻塞 IO</code>。阻塞是体现在哪里了？</p>
<p>首先给个结论：它会从头阻塞到尾！</p>
<p>我们通过下图进行理解：</p>
<p><img src="http://p5h71khzd.bkt.clouddn.com/%E9%98%BB%E5%A1%9Eio.png" alt="阻塞IO"></p>
<p>一个应用读取到数据，其实是经过了2个流程。</p>
<ol>
<li>数据先是通过<code>网络</code>填充满<code>系统内核</code></li>
<li>然后从<code>系统内核</code>读取到<code>应用程序（用户空间）</code></li>
</ol>
<blockquote>
<p>上述2个流程很重要，请用心背住并多加理解。</p>
</blockquote>
<p><code>BIO</code>在每一次<code>IO</code>读取上，会在第一个流程开始到第二个流程结束这个<code>全过程中阻塞</code>。</p>
<p>结合具体的业务来讲：客户端同服务端每建立一个连接进行数据传输时，服务端就需要1个线程等待上述进行1和2完成后，才能进行后续收集到的数据的处理任务。</p>
<p>这个过程意味着，服务端需要同N个客户端进行通信，那么在服务端就需要N个线程进行监听。</p>
<h1 id="非阻塞-IO：NIO"><a href="#非阻塞-IO：NIO" class="headerlink" title="非阻塞 IO：NIO"></a>非阻塞 IO：NIO</h1><p>NIO 也就是 <code>同步非阻塞 IO</code>,它优化了传统 IO 在上述流程中的第1步。</p>
<p>这里的非阻塞指的就是：在第一个流程中，判定系统内核的数据是否可读上，是非阻塞的，是通过不停轮询进行判定的。</p>
<p>具体而言如下图所示：</p>
<p><img src="http://p5h71khzd.bkt.clouddn.com/%E9%9D%9E%E9%98%BB%E5%A1%9EIO.png" alt="非阻塞IO"></p>
<p>异步IO 在第一个流程中，线程会不段的轮询去获取系统内核的数据是否就位这个状态，如果就位了，才能将数据从系统内核拷贝到用户空间。在第一个流程中，系统是没有被阻塞的，但是却是在不停的进行轮询判定。</p>
<blockquote>
<p>这个地方其实我也是有疑问的：</p>
<p><code>非阻塞IO</code>对于<code>阻塞IO</code>而言，<code>非阻塞IO</code>在第一个流程确实是阻塞，但是其却是只能通过不停轮询判定数据是否可读的状态。这样做，性能上有何提升？</p>
<p>望有高手能够解答下这个疑惑！</p>
</blockquote>
<h1 id="IO多路复用"><a href="#IO多路复用" class="headerlink" title="IO多路复用"></a>IO多路复用</h1><p><code>IO多路复用</code>是在<code>NIO</code>基础的改进，Netty就是基于<code>IO多路复用</code>进行数据接收的。</p>
<p><img src="http://p5h71khzd.bkt.clouddn.com/io%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8.png" alt="IO多路复用"></p>
<p>首先<code>IO多路</code>在不同系统的不同模式下实现是由细微差异的，不过大体的流程一致。</p>
<p>在第一个阶段上：</p>
<ul>
<li>每一个连接都会注册到系统的 <code>系统内核</code>上。</li>
<li>系统通过某种手段<code>（select\poll\epoll）</code> 判定当前数据是否可读，当可读的时候通过<code>callback</code>事件回调的方式，进行后续数据处理。</li>
</ul>
<blockquote>
<ol>
<li>select和poll模型支持的<code>fd</code>有限，且对于<code>fd</code>的扫描是<code>顺序扫描</code>，所以高并发下性能不好。</li>
<li>Linux下的<code>epoll</code>模型支持更多的<code>fd</code>和<code>基于活跃扫描并回调</code>的方式进行处理，所以高并发下性能更好。</li>
</ol>
</blockquote>
<p>还有一点需要指出：<strong>通过IO多路复用，可以1个线程支持多个连接，这个是上述IO模型不具备的。</strong></p>
<h1 id="异步IO：AIO"><a href="#异步IO：AIO" class="headerlink" title="异步IO：AIO"></a>异步IO：AIO</h1><p><code>异步IO</code>是<code>异步非阻塞IO</code>，性能更强大了，全程都是基于<code>callback</code>的。</p>
<p>如下图所示：</p>
<p><img src="http://p5h71khzd.bkt.clouddn.com/%E5%BC%82%E6%AD%A5io.png" alt="异步IO"></p>
<h1 id="举例说明"><a href="#举例说明" class="headerlink" title="举例说明"></a>举例说明</h1><p>我们通过一个现实的例子来举例：我们去银行办理业务，需要先填写业务表单，然后才能进行后续的业务。</p>
<p>传统的 IO就是：你走到柜台后，柜台小姐姐盯着你填写业务表单，后续给你办理业务。在填写表单到后续业务处理的过程，柜台小姐姐会一直为你服务。这个过程中你填写业务表达的过程的时候，柜台小姐姐就只是盯着你而已，并没有做什么工作，存在资源浪费。</p>
<p>多路复用就是：你先到银行大厅填表，当你填写完成后你告诉大厅分流的小姐姐我填写完成了，然后由她给你安排一个操作柜台进行后续业务处理。</p>
<blockquote>
<p>说实话，这篇文章，修改了几次，随着个人理解加深，很多地方感觉还是不够，希望大家多多指点。</p>
</blockquote>
<h1 id="参考地址"><a href="#参考地址" class="headerlink" title="参考地址"></a>参考地址</h1><p><a href="https://github.com/CyC2018/Interview-Notebook/blob/master/notes/Socket.md" target="_blank" rel="noopener">https://github.com/CyC2018/Interview-Notebook/blob/master/notes/Socket.md</a></p>
<p><a href="https://blog.csdn.net/woaixiaopangniu521/article/details/70279143" target="_blank" rel="noopener">https://blog.csdn.net/woaixiaopangniu521/article/details/70279143</a></p>
<blockquote>
<p>您有任何建议和意见，请Email联系: <a href="mailto:hicode_club@163.com" target="_blank" rel="noopener">hicode_club@163.com</a></p>
<p>转载请保留出处 <a href="http://www.hicode.club" target="_blank" rel="noopener">HiCode 俱乐部</a></p>
</blockquote>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/04/16/mac-intellij-terminal/" rel="next" title="Mac下在终端启动 Intellij">
                <i class="fa fa-chevron-left"></i> Mac下在终端启动 Intellij
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/22/thread-local-1/" rel="prev" title="ThreadLocal自我总结（一）">
                ThreadLocal自我总结（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">文敦复</p>
              <p class="site-description motion-element" itemprop="description">思考的懒惰是真的懒惰！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">37</span>
                    <span class="site-state-item-name">categories</span>
                  
                </div>
              

              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#需求背景"><span class="nav-number">1.</span> <span class="nav-text">需求背景</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#阻塞-IO：BIO"><span class="nav-number">2.</span> <span class="nav-text">阻塞 IO：BIO</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#非阻塞-IO：NIO"><span class="nav-number">3.</span> <span class="nav-text">非阻塞 IO：NIO</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#IO多路复用"><span class="nav-number">4.</span> <span class="nav-text">IO多路复用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#异步IO：AIO"><span class="nav-number">5.</span> <span class="nav-text">异步IO：AIO</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#举例说明"><span class="nav-number">6.</span> <span class="nav-text">举例说明</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考地址"><span class="nav-number">7.</span> <span class="nav-text">参考地址</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文敦复</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme – <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Muse</a> v6.4.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.0"></script>



  



  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
